<template>
    <div class="edu-page-warp">
        <!-- <div class="edu-page-title">{{ $t('information.myInformationRelease') }}</div> -->
        <div class="edu-page-title">{{ $t('workbench.systemNotice') }}</div>
        <el-card class="body-card" shadow="never">
            <div class="table-operate">
                <el-button class="operate-add" type="primary" @click="addInformation">新增</el-button>
                <el-button class="operate-add" type="primary" @click="invalidateInformations">批量失效</el-button>
            </div>
            <el-table
                :data="myInformationList"
                ref="myInformationTable"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="45"/>
                <el-table-column prop="msgTitle" label="信息标题" show-overflow-tooltip="true">
                    <template slot-scope="scope">
                        <a @click="viewInformation(scope.row.id)">
                            <span>[{{ scope.row.schoolRangeLabel }}]</span>
                            <span>[{{ scope.row.typeLabel }}]</span>
                            <span>{{ scope.row.title }}</span>
                        </a>
                    </template>
                </el-table-column>
                <el-table-column label="发布日期" prop="createTime" width="120"></el-table-column>
                <el-table-column :label="$t('information.titleStatus')" width="120">
                    <template slot-scope="scope">
                        <span>
                            <el-tag v-if="scope.row.status == '1'" type="info">草稿</el-tag>
                            <el-tag v-if="scope.row.status == '2'" type="warning">审核中</el-tag>
                            <template v-if="scope.row.status == '3'">
                                <el-tag v-if="scope.row.tagStatus == '2'" type="danger">失效</el-tag>
                                <el-tag v-else type="success">已发布</el-tag>
                            </template>
                        </span>
                    </template>
                </el-table-column>
                <el-table-column :label="$t('message.operating')" width="200">
                    <template slot-scope="scope">
                        <el-button
                            v-if="scope.row.status == '1'"
                            type="text"
                            @click="checkInformation(scope.row.id)"
                        >提交</el-button>
                        <el-button
                            v-if="scope.row.status == '1'"
                            type="text"
                            @click="editInformation(scope.row.id)"
                        >{{$t('message.edit')}}</el-button>
                        <el-button
                            v-if="scope.row.tagStatus != '2' && scope.row.status == '3'"
                            type="text"
                            @click="invalidateInformation(scope.row.id)"
                        >失效</el-button>
                        <!-- <el-button type="text" @click="viewInformation(scope.row.id)">查看</el-button> -->
                        <el-button
                            v-if="scope.row.status == '1'"
                            type="text"
                            @click="delInformation(scope.row.id)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-row>
                <el-col>
                    <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handlePageNumChange"
                        :current-page="searchParam.pageNum_"
                        :page-sizes="[20,50,100,500,1000]"
                        :page-size="searchParam.pageSize_"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="searchParam.total"
                        style="float: right;margin:10px 0 0 0;"
                    ></el-pagination>
                </el-col>
            </el-row>
        </el-card>
        <el-dialog
            title="信息公告"
            width="45%"
            :visible.sync="showInfoViewDialog"
            :close-on-click-modal="false"
        >
            <div class="information-view">
                <h1 class="info-title">{{information.title}}</h1>
                <div class="info-date">发布日期：{{information.createTime}}</div>
                <div class="info-content" v-html="information.content"></div>
                <div class="info-attach">
                    <div v-for="(attach,index) in information.commonAttachmentList" :key="index">
                        <div class="attach-item" @click="handleDownloadfile(attach.fileLacation, attach.fileName)">
                            <i class="el-icon-document"></i>
                            <span class="attach-name">{{attach.fileName}}</span>
                        </div>
                    </div>
                </div>
            </div>
        </el-dialog>
        <el-dialog
            title="信息公告"
            width="45%"
            :visible.sync="showInfoViewDialog"
            :close-on-click-modal="false"
        >
            <div class="information-view">
                <h1 class="info-title">{{information.title}}</h1>
                <div class="info-date">发布日期：{{information.createTime}}</div>
                <div class="info-content" v-html="information.content"></div>
                <div class="info-attach">
                    <div v-for="attach in information.commonAttachmentList">
                        <div class="attach-item" @click="handleDownloadfile(attach.fileLacation, attach.fileName)">
                            <i class="el-icon-document"></i>
                            <span class="attach-name">{{attach.fileName}}</span>
                        </div>
                    </div>
                </div>
            </div>
        </el-dialog>
        <el-dialog
            title="提交审核"
            width="45%"
            :visible.sync="showInfoCheckDialog"
            :close-on-click-modal="false"
        >
            <div class="information-view">
                <el-form
                    :model="informationCheckForm"
                    ref="informationCheckForm"
                    label-width="90px"
                    :rules="checkRules"
                >
                    <el-row :gutter="20">
                        <el-col :span="6">{{$t('information.label')}} {{ information.labelKey }}</el-col>
                        <el-col :span="6">{{$t('information.type')}} {{ information.typeLabel }}</el-col>
                        <el-col
                            :span="6"
                        >{{$t('information.institutionalScope')}} {{ information.schoolRangeLabel }}</el-col>
                        <el-col
                            :span="6"
                        >{{$t('information.teacherAndStudentRange')}} {{ information.tsRangeLabel }}</el-col>
                    </el-row>
                    <h1 class="info-title">{{information.title}}</h1>
                    <div class="info-date">发布日期：{{information.createTime}}</div>
                    <div class="info-content" v-html="information.content"></div>
                    <div class="info-attach">
                        <div v-for="attach in information.commonAttachmentList">
                            <div
                                class="attach-item"
                                @click="handleDownloadfile(attach.fileLacation, attach.fileName)"
                            >
                                <i class="el-icon-document"></i>
                                <span class="attach-name">{{attach.fileName}}</span>
                            </div>
                        </div>
                    </div>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="材料说明:" prop="editExplain">
                                <el-input
                                    type="textarea"
                                    :rows="3"
                                    placeholder="请输入内容"
                                    v-model="informationCheckForm.editExplain"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="证明材料:" prop="informationFiles">
                                <el-upload
                                    :headers="{'X-Token': $store.state.session.sessionid}"
                                    :data="{bucketname: 'face', folderpath: 'file'}"
                                    :on-remove="handleFileRemove"
                                    :on-success="handleUploadSuccess"
                                    :file-list="informationFileList"
                                    class="upload-demo"
                                    action="/api/commonservice/obsfile/uploadfile"
                                    multiple
                                >
                                    <el-button class="operate-add" type="primary">上传附件</el-button>
                                </el-upload>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <div class="btn-list">
                                <el-button @click="showInfoCheckDialog=false">取消</el-button>
                                <el-button type="primary" @click="handleCheckCommonPublicMsg">确定</el-button>
                            </div>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
        </el-dialog>
        <el-dialog
            title="提示"
            :visible.sync="confirmCheckDialogVisible"
            :show-close="false"
            width="35%"
        >
            <span>信息公告已提交审核，可前往我的信息发布中查看审批进度</span>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="refreshMyInformation">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import {
    findCommonPublicMsgList,
    findCommonPublicMsgById,
    updateTagStatus,
    deleteCommonPublicMsg,
    checkCommonPublicMsg
} from "common/src/api/public/information";
import InformationView from "./InformationView";
import { queryDic } from "common/src/api/dictionary";
import { downloadfile } from "common/src/api/upload";
import filters from "common/src/filters";
import Bus from "common/src/utils/bus";

export default {
    name: "myInformation",
    components: {
        "information-view": InformationView
    },
    data() {
        return {
            myInformationList: [],
            searchParam: {
                pageNum_: 1,
                pageSize_: 20
            },
            options: {
                labelList: [],
                typeList: [],
                institutionalScopeList: [],
                teacherAndStudentRangeList: []
            },
            invalidateRows: [],
            showInfoViewDialog: false,
            showInfoCheckDialog: false,
            viewInforamtionId: "",
            information: {},
            informationCheckForm: {
                type: 20
            },
            informationFiles: "",
            checkRules: {
                editExplain: [
                    {
                        required: true,
                        message: this.$t("information.msg.editExplain"),
                        trigger: "blur"
                    }
                ]
            },
            informationFileList: [],
            confirmCheckDialogVisible: false
        };
    },
    mounted() {
        this.getOptions();
    },
    methods: {
        handleDownloadfile(objectkey, filename) {
            if (!objectkey) return;
            downloadfile(filename ? objectkey + `&realName=${filename}` : objectkey);
        },
        searchMyInformations() {
            if (this.$route.query.isHomeJump) {
                this.searchParam.status = this.$route.query.status;
                this.searchParam.tagStatus = this.$route.query.tagStatus;
            }
            findCommonPublicMsgList(this.searchParam).then(res => {
                if (res.code == 200) {
                    this.myInformationList = res.data.list.map(item => {
                        item.createTime = filters.formatDate(
                            item.createTime,
                            "yyyy/MM/dd"
                        );
                        this.setInformationDic(item);
                        return item;
                    });
                    this.searchParam.pageNum_ = res.data.pageNum_;
                    this.searchParam.pageSize_ = res.data.pageSize_;
                    this.searchParam.total = res.data.total_;
                }
            });
        },
        setInformationDic(item) {
            // 获取对应的类型
            this.options.typeList.forEach(type => {
                if (type.value == item.type) {
                    item.typeLabel = type.label;
                }
            });
            // 获取对应的师生范围
            this.options.teacherAndStudentRangeList.forEach(
                // 字段搞错了(同志伟沟通) tsRange代表师生范围 schoolRange 代表校院范围 
                teacherAndStudentRange => {
                    if (teacherAndStudentRange.value == item.tsRange) {
                        item.tsRangeLabel = teacherAndStudentRange.label;
                    }
                }
            );
            // 获取对应的标签
            this.options.labelList.forEach(labelItem => {
                if (labelItem.value == item.label) {
                    item.labelKey = labelItem.label;
                }
            });
            // 获取对应的校院范围
            this.options.institutionalScopeList.forEach(institutionalScope => {
                // 字段搞错了(同志伟沟通) tsRange代表师生范围 schollRange 代表校院范围 
                if (institutionalScope.value == item.schoolRange) {
                    item.schoolRangeLabel = institutionalScope.label;
                }
            });
        },
        handleSelectionChange(rows) {
            this.invalidateRows = rows;
        },
        invalidateInformations() {
            if (this.invalidateRows.length == 0) {
                this.$message({
                    type: "warning",
                    message: "请选择要失效的信息公告"
                });
            } else {
                const ids = this.invalidateRows
                    .filter(item => item.status == "3")
                    .map(item => item.id);
                if (ids && ids.length == 0) {
                    this.$message({
                        type: "warning",
                        message: "没有选择已发布的信息公告"
                    });
                } else {
                    this.$confirm("是否确认失效已发布的信息公告?", "提示", {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning"
                    }).then(() => {
                        updateTagStatus({ ids }).then(res => {
                            this.$message({
                                type: "success",
                                message: "操作成功!"
                            });
                            // 刷新信息列表
                            this.searchMyInformations();
                            // 清空选择
                            this.$refs.myInformationTable.clearSelection();
                            this.invalidateRows = [];
                        });
                    });
                }
            }
        },
        checkInformation(id) {
            findCommonPublicMsgById(id).then(res => {
                this.information = res.data;
                this.setInformationDic(this.information);
                this.information.createTime = filters.formatDate(
                    this.information.createTime,
                    "yyyy/MM/dd"
                );
                // 显示审核信息
                this.showInfoCheckDialog = true;
                this.informationCheckForm.id = id;
            });
        },
        handleCheckCommonPublicMsg() {
            this.$refs.informationCheckForm.validate(valid => {
                if (!valid) {
                    return;
                }
                if (this.informationFileList.length == 0) {
                    this.$message({
                        type: "error",
                        message: "请上传证明材料!"
                    });
                    return;
                }
                checkCommonPublicMsg(this.informationCheckForm).then(res => {
                    if (res.code == 200) {
                        this.handleCheckSuccess();
                    }
                });
            });
        },
        handleCheckSuccess() {
            this.showInfoCheckDialog = false;
            this.confirmCheckDialogVisible = true;
        },
        refreshMyInformation() {
            this.confirmCheckDialogVisible = false;
            this.searchMyInformations();
        },
        editInformation(id) {
            this.$router.push(`/informationRelease/${id}`);
        },
        invalidateInformation(id) {
            this.$confirm("该公告是否确认失效?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                updateTagStatus({ ids: [id] }).then(res => {
                    this.$message({ type: "success", message: "操作成功!" });
                    // 刷新信息列表
                    this.searchMyInformations();
                });
            });
        },
        viewInformation(id) {
            // this.showInfoViewDialog = true;
            // this.viewInforamtionId = id;
            findCommonPublicMsgById(id).then(res => {
                this.information = res.data;
                this.information.createTime = filters.formatDate(
                    this.information.createTime,
                    "yyyy/MM/dd"
                );
                // 显示查看信息
                this.showInfoViewDialog = true;
            });
        },
        delInformation(id) {
            this.$confirm("您确定要删除吗?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                deleteCommonPublicMsg({ ids: [id] }).then(res => {
                    this.$message({ type: "success", message: "操作成功!" });
                    // 刷新信息列表
                    this.searchMyInformations();
                });
            });
        },
        handlePageNumChange(val) {
            this.searchParam.pageNum_ = val;
            this.searchMyInformations();
        },
        handleSizeChange(val) {
            this.searchParam.pageSize_ = val;
            this.searchMyInformations();
        },
        addInformation: function() {
            // this.showDictDialog = true;
            this.$router.push("/informationRelease/");
        },
        getOptions() {
            const data = {
                lang: this.$store.getters.language || "cn",
                type: "allChild",
                keys: ["K_LABEL", "K_XXLX", "K_XYFW", "K_SSFW"]
            };
            queryDic(data).then(res => {
                if (res.code === 200) {
                    this.fillSelect(res.data);
                    // 查询我的信息发布
                    this.searchMyInformations();
                }
            });
        },
        fillSelect(data) {
            let { K_LABEL, K_XXLX, K_XYFW, K_SSFW } = data;
            this._fill("labelList", K_LABEL);
            this._fill("typeList", K_XXLX);
            this._fill("institutionalScopeList", K_XYFW);
            this._fill("teacherAndStudentRangeList", K_SSFW);
        },
        _fill(type, data) {
            for (const key in data) {
                this.options[type].push({
                    value: key,
                    label: data[key]
                });
            }
        },
        handleFileRemove(file, fileList) {
            this.informationFileList = fileList;
            if (fileList.length > 0) {
                this.informationFiles = "uploaded";
            } else {
                this.informationFiles = "";
            }
            this.informationCheckForm.evidenceList = this.setInformationAttachList(
                fileList
            );
        },
        handleUploadSuccess(res, file, fileList) {
            if (fileList.length > 0) {
                this.informationFiles = "uploaded";
            } else {
                this.informationFiles = "";
            }
            this.informationFileList = fileList;
            this.informationCheckForm.evidenceList = this.setInformationAttachList(
                fileList
            );
        },
        setInformationAttachList(fileList) {
            let attachList = [];
            fileList.forEach(item => {
                if (item.response && item.response.data) {
                    const uploadedObj = item.response.data[item.name];
                    if (uploadedObj) {
                        attachList.push(uploadedObj.objectkey);
                    }
                }
            });
            return attachList;
        }
    }
};
</script>
<style lang="scss" scoped>
.body-card {
    padding: 10px;
}
.table-operate {
    padding-bottom: 15px;
    text-align: right;
    .operate-add {
        margin-right: 10px;
    }
}
.information-view {
    .info-title {
        margin-top: 25px;
    }
    .info-title,
    .info-date {
        text-align: center;
    }
    .info-content {
        margin-top: 15px;
        max-width: 100%;
    }
    .info-attach {
        padding: 10px 0;
        .attach-item {
            display: inline-block;
            padding: 3px 0;
            .attach-name {
                margin-left: 5px;
                cursor: pointer;
            }
            &:hover {
                .attach-name {
                    color: #409eff;
                }
            }
        }
    }
    .btn-list {
        text-align: right;
    }
}
</style>
